package com.highstockings.service.impl;

import com.github.pagehelper.PageHelper;
import com.highstockings.dao.ArticleMapper;
import com.highstockings.dao.GalleryTypeMapper;
import com.highstockings.dao.ModelMapper;
import com.highstockings.model.Article;
import com.highstockings.model.ArticleDetailsVo;
import com.highstockings.model.GalleryType;
import com.highstockings.model.Model;
import com.highstockings.service.ArticleService;
import com.highstockings.utils.FileUtil;
import com.highstockings.utils.ImageUtil;
import com.highstockings.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationHome;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by diablo13064 on 2018/3/28.
 */
@Service("ArticleService")
public class ArticleServiceImpl implements ArticleService{
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    GalleryTypeMapper galleryTypeMapper;
    @Autowired
    QiniuUtil qiniuUtil;
    @Autowired
    ImageUtil imageUtil;
    //private static String dir = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/static/upload/";
    private String dir = getJarFileDir() + File.separator + "upload" + File.separator;

    @Override
    public int addArticle(Article article) throws Exception {
        Article article1 = combineArticleInfo(article);
        return articleMapper.insert(article1);
    }
    @Override
    public List<Article> selectFivePics() {
        return articleMapper.selectArticleImageInfo();
    }
    @Override
    public List<Article> findAllArticle() {
        return articleMapper.selectAllArticle();
    }

    @Override
    public ArticleDetailsVo findArticleDeitalsById(int id) {
        return articleMapper.selectArticleDetailsById(id);
    }

    @Override
    public List<ArticleDetailsVo> findAllArticleDetails() {
        return articleMapper.selectAllArticleDetails();
    }

    @Override
    public int addViewCount(int aid) {
        return articleMapper.updateViewCount(aid);
    }

    @Override
    public int addUpCount(int aid) {
        return articleMapper.updateUpCount(aid);
    }

    @Override
    public int addDownCount(int aid) {
        return articleMapper.updateDownCount(aid);
    }

    @Override
    public Set<String> findAllTagName() {
        return FileUtil.tagSeperators(articleMapper.selectTagName());
    }

    @Override
    public List<ArticleDetailsVo> findSideBarInfo1() {
        return articleMapper.selectSideBarInfo1();
    }

    @Override
    public List<ArticleDetailsVo> findArticleByCountry(String country, int pageNum,int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleDetailsVo> list = articleMapper.selectArticleByCountry(country);
        return  FileUtil.enhancedTagSet(list);
    }

    @Override
    public List<ArticleDetailsVo> findArticleByTag(String tag, int pageNum,int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleDetailsVo> list = articleMapper.selectArticleByTag(tag);
        return FileUtil.enhancedTagSet(list);
    }

    public List<ArticleDetailsVo> findArticleByContidtions(String column, String value, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleDetailsVo> list = new ArrayList<>();
        switch (column) {
            //文章ID
            case "AID":
                int aid = Integer.parseInt(value);
                break;
            //国家
            case "COUNTRY":

                break;
            //标签
            case "TAG":

                break;
            //MODELID
            case "MODELID":
                int mid = Integer.parseInt(value);
                break;
            //文章分类
            case "ARTICLETYPE":
                int articletype = Integer.parseInt(value);
                break;

        }
        return FileUtil.enhancedTagSet(list);
    }

    @Override
    public List<ArticleDetailsVo> findArticleByModelId(int mid, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return  FileUtil.enhancedTagSet(articleMapper.selectArticleByModelId(mid));
    }

    @Override
    public int changeState(String status, int aid) {
        return articleMapper.updateStatus(status,aid);
    }

    /**
     * @param article:表单上传的文章信息
     * @return
     */
    public Article combineArticleInfo(Article article) throws Exception {
        //临时设置
        article.setAuthorid(1);

        //从Title中提取信息
        Date c = Calendar.getInstance().getTime();
        Map<String, String> articleInfo = FileUtil.enhancedArticleInfo(article);
        try {
            article.setCreatetime(articleInfo.get("createTime") != null ? new SimpleDateFormat("yyyy.MM.dd").parse(articleInfo.get("createTime")) : c);            //填充添加时间
            article.setFilecounter(articleInfo.get("fileCounter") != null ? Integer.parseInt(articleInfo.get("fileCounter")) : 0);                                    //填充文件数
            article.setFilesize(articleInfo.get("fileSize") != null ? articleInfo.get("fileSize") : "999");                  //填充文件大小
        } catch (Exception e) {

        }

        //System.out.println(articleInfo.get("alias").length());
        //填充模特信息
        if (articleInfo.get("alias").length() > 3) {
            if (modelMapper.selectByAlias(articleInfo.get("alias")) != null) {
                article.setModelid(modelMapper.selectByAlias(articleInfo.get("alias")).getMid());
            } else {
                Model model = new Model();
                model.setAlias(articleInfo.get("alias"));
                modelMapper.insertSelective(model);
                model = modelMapper.selectByAlias(articleInfo.get("alias"));
                article.setModelid(model.getMid());
            }
        } else {
            article.setModelid(0);
        }
        //填充图库信息
        if (articleInfo.get("galleryType").length() > 3) {
            if (galleryTypeMapper.selectNameByType(articleInfo.get("galleryType")) != null) {
                article.setArticletype(galleryTypeMapper.selectNameByType(articleInfo.get("galleryType")).getTid());
            } else {
                GalleryType galleryType = new GalleryType();
                galleryType.setLibrarytype(articleInfo.get("galleryType"));
                galleryTypeMapper.insertSelective(galleryType);
                galleryType = galleryTypeMapper.selectNameByType(articleInfo.get("galleryType"));
                article.setArticletype(galleryType.getTid());
            }
        }
        //文件编号
        article.setFilenumber(new SimpleDateFormat("yyyyMMdd").format(c) +
                String.valueOf(article.getModelid() != null ? article.getModelid() : "99" + article.getArticletype() != null ? article.getArticletype() : "99" + article.getFilecounter() != null ? article.getFilecounter() : "99"));

        //处理图片文件
        File pics_dir = new File(dir);
        for (File f : pics_dir.listFiles()) {
            if (!f.getName().endsWith(".jpg")) {
                continue;
            }
            qiniuUtil.upload(FileUtil.File2byte(f.getAbsolutePath()), f.getName());
            if (f.getName().contains("cover")) {                        //cover是展示图片1
                article.setImglink1(qiniuUtil.getSecretDownLink(f.getName()));
            } else {
                int[] pic_size = ImageUtil.getSizeInfo(f);
                if (pic_size[0] > pic_size[1]) {
                    article.setFrontcover(qiniuUtil.getSecretDownLink(f.getName()));                                 //宽屏是封面展示
                    /*换封面*/
                    /*String pic_cover = dir.replace("/upload/", "")+"/build/images/slider/";
                    File covers = new File(pic_cover + f.getName());
                    if (!covers.exists()) {
                        covers.createNewFile();
                    }
                    FileCopyUtils.copy(f, covers);*/
                    continue;
                }
                if (article.getImglink2() == null) {
                    article.setImglink2(qiniuUtil.getSecretDownLink(f.getName()));                                  //展示2
                    continue;
                }
                if (article.getImglink3() == null) {
                    article.setImglink3(qiniuUtil.getSecretDownLink(f.getName()));                                      //展示3
                }
                //if(article.getImglink1()==null && article.get)
            }
        }
        return article;
    }

    public String getUploadDir() {
        return dir;
    }

    @Override
    public List<ArticleDetailsVo> findArticleHome(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return FileUtil.enhancedTagSet(articleMapper.selectArticleHome());
    }

    private String getJarFileDir() {
        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        return jarFile.getParentFile().getAbsolutePath();
    }

}
